<template>
  <div class="page">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
      <el-form-item label="归属单位">
        <el-select v-model="formInline.matter" placeholder="事项">
          <el-option v-for="(item,index) in companyList" :key="index" :label="item.company" :value="item.company" />
        </el-select>
      </el-form-item>
      <el-form-item label="购买日期">
        <el-date-picker
          v-model="formInline.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="版本型号">
        <el-input v-model="formInline.type" placeholder="请输入版本型号" />
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addModelClick">新增</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{background:'#F2F2F2',color:'#333333'}"
        style="width: 100%"
      >
        <el-table-column
          label="序号"
          type="index"
          width="60"
        />
        <el-table-column
          prop="version"
          label="版本型号"
          width="150"
        />
        <el-table-column label="归属单位" prop="company" />
        <el-table-column label="购买日期" prop="purchase_date" />
        <el-table-column label="使用日期" prop="use_date" />
        <el-table-column label="绑定工作人员姓名" prop="working_personnel" />
        <el-table-column label="工作人员联系电话" prop="tel" />
        <el-table-column label="操作" width="190" align="right">
          <template slot-scope="scope">

            <div v-if="scope.row.binding_status && scope.row.status" class="info_button">
              <span class="sell_name" :style="blue" @click="bindingClick(scope.row)">{{ scope.row.binding_status }}</span>
              <span v-if="scope.row.status == '启用'" class="info_button" @click="stopUsingClick(scope.row)">{{ scope.row.status }}</span>
              <span v-else :style="red" class="info_button" @click="stopUsingClick(scope.row)">{{ scope.row.status }}</span>
              <span class="info_button" :style="red" @click="deleteRow(scope.row.id)">删除</span>
            </div>

            <div v-else class="info_button">
              <span class="sell_name" @click="bindingClick(scope.row)">{{ scope.row.binding_status || '绑定' }}</span>
              <span v-if="scope.row.status == '停用'" class="info_button" :style="red" @click="stopUsingClick(scope.row)">{{ scope.row.status }}</span>
              <span v-else class="info_button" @click="stopUsingClick(scope.row)">{{ scope.row.status || '启用' }}</span>
              <span class="sell_name" :style="red" @click="deleteRow(scope.row.id)">删除</span>
            </div>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      :page-size.sync="page.pageSize"
      :total="page.total"
      :current-page.sync="page.pageIndex"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!--录入弹框-->
    <add-equipment @addFun="getAddData" :addModelShow="addEquipmentShow" />
    <!--绑定人员信息-->
    <div>
      <el-dialog title="绑定人员" :visible.sync="bindingShow" width="550px" :before-close="cancleBtn">
        <div class="container_examine">
          <div>
            <el-form ref="ruleForm" label-position="top" :model="form" label-width="80px">
              <!--              <el-form-item label="工作人员" prop="unit" >-->
              <!--                <el-select v-model="form.people" placeholder="请选择机构部门" >-->
              <!--                  <el-option v-for="item in peopleList " :key="item.id" :label="item.name" :value="item.id" style="height: 40px;overflow: auto" />-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->
              <el-form-item label="工作人员" prop="unit">
                <el-cascader
                  style="width: 100%"
                  v-model="form.people"
                  :options="unitList"
                  ref="myCascader"
                  :props="{label:'name',value:'code'}"
                  @change="handleChange"></el-cascader>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancleBtn">取消</el-button>
          <el-button size="small" type="primary" @click="saveBtn">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { dateFormat } from '../utils'
  import {getManagementList, bindingInfo, getBindingName, getCompanyList, getStructureList, deleteRowList,delDevice} from '../api'
  // 录入弹框
  import AddEquipment from '../components/AddEquipment'
  export default {
    name: 'Management',
    components: {
      AddEquipment
    },
    data() {
      return {
        red: 'color: #F66363',
        orange: 'color: #FB7A11',
        green: 'color: #1DC989',
        yellow: 'color:#FDC800',
        blue: '#1182FB',
        formInline: {
          matter: '全部',
          time: '',
          type: '',
          start_time: '',
          end_time: ''
        },
        form: {
          people: '',
          name: '',
          tel: ''
        },
        tableData: [],
        page: {
          pageSize: 12,
          pageIndex: 1,
          total: 0
        },
        loading: false,
        bindingShow: false,
        peopleList: [],
        rowList: {},
        companyList: [{
          company: '全部'
        }],
        addEquipmentShow:false,
        unitList:[]
      }
    },
    computed: {

    },
    watch: {
      'formInline.time': function(newVal) {
        this.formInline.start_time =
          newVal != null
            ? this.formatTime(newVal[0])
            : ''
        this.formInline.end_time =
          newVal != null
            ? this.formatTime(newVal[1])
            : ''
      },
      'form.people': function(newVal) {
        this.peopleList.map((item) => {
          if (item.id === newVal) {
            this.form.name = item.name
            this.form.tel = item.telephone
          }
        })
      }
    },
    created() {
      this.getDataList()
      this.getCompany()
      this.getStructureList()
    },
    mounted() {
      console.log()
    },
    methods: {
      // 获取机构列表
      getStructureList() {
        getStructureList('派发').then(res => {
          this.unitList = res.data.data.sjlist;
        })
      },
      // 时间格式化
      formatTime(time) {
        return time ? dateFormat(new Date(time), 'yyyy-MM-dd') : ''
      },
      // 获取列表信息
      getDataList() {
        const data = {
          company: this.formInline.matter === '全部' ? '' : this.formInline.matter,
          version: this.formInline.type,
          start_time: this.formInline.start_time,
          end_time: this.formInline.end_time,
          page: this.page.pageIndex,
          limit: this.page.pageSize
        }
        this.loading = true
        getManagementList(data).then(res => {
          this.loading = false
          this.tableData = res.data.data.list
          this.page.total = res.data.data.totalRow
        })
      },
      // 获取归属单位
      getCompany() {
        getCompanyList().then(res => {
          res.data.map((item) => {
            this.companyList.push(item)
          })
        })
      },
      // 获取绑定人员名单
      getPeopleList() {
        getBindingName().then(res => {
          this.peopleList = res.data
        })
      },
      bindingClick(row) {
        if (row.binding_status === '解除绑定') {
          this.rowList = row
          this.saveBtn()
        } else {
          this.getPeopleList()
          this.bindingShow = true
          this.rowList = row
        }
      },
      saveBtn() {
        if (this.rowList.binding_status === '解除绑定') {
          this.$confirm('您确定要解除绑定吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const data = {
              type: '绑定',
              status: this.rowList.binding_status == null ? '绑定' : this.rowList.binding_status,
              id: this.rowList.id,
              ryid: this.form.people,
              name: this.form.name,
              tel: this.form.tel
            }
            bindingInfo(data).then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '解除绑定成功'
                })
                this.bindingShow = false
                this.form.people = ''
                this.form.name = ''
                this.form.tel = ''
                this.getDataList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.msg
                })
              }
            })
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消'
            // });
          })
        } else {
          if(this.form.name){
            const data = {
              type: '绑定',
              status: this.rowList.binding_status == null ? '绑定' : this.rowList.binding_status,
              id: this.rowList.id,
              ryid: this.form.people,
              name: this.form.name
            }
            console.log(data)
            bindingInfo(data).then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '绑定成功'
                })
                this.bindingShow = false
                this.form.people = ''
                this.form.name = ''
                this.form.tel = ''
                this.getDataList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.msg
                })
              }
            })
          }else{
            this.$message.warning('机构部门不能为空')
          }


        }
      },
      stopUsingClick(row) {
        if (row.status === '停用') {
          this.$confirm('您确定要停用吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const data = {
              type: '启用',
              status: row.status == null ? '启用' : row.status,
              id: row.id,
              ryid: this.form.people,
              name: this.form.name,
              tel: this.form.tel
            }
            bindingInfo(data).then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '停用成功'
                })
                this.getDataList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.msg
                })
              }
            })
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // });
          })
        } else {
          this.$confirm('您确定要启用吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const data = {
              type: '启用',
              status: row.status == null ? '启用' : row.status,
              id: row.id,
              ryid: this.form.people,
              name: this.form.name,
              tel: this.form.tel
            }
            bindingInfo(data).then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '启用成功'
                })
                this.getDataList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.msg
                })
              }
            })
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // });
          })
        }
      },
      deleteRow(id) {
        this.$confirm('确认删除该数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.cancelButtonLoading = true
              instance.confirmButtonText = '删除中，请耐心等待...'
              delDevice(id)
                .then((res) => {
                  if (res.data.code == 200) {
                    this.$message({
                      type: 'success',
                      message: '删除成功!'
                    })

                    this.getDataList()
                  } else {
                    this.$message({
                      type: 'error',
                      message: res.data
                    })
                  }
                })
                .finally(() => {
                  instance.confirmButtonLoading = false
                  instance.cancelButtonLoading = false
                  done()
                })
            } else {
              done()
            }
          }
        }).catch(() => {})
      },
      onSubmit() {
        this.getDataList()
      },
      getAddData(data) {
        if(data){
          this.getDataList()
        }
        this.addEquipmentShow = false;
      },
      addModelClick() {
        this.addEquipmentShow = true;
      },
      handleChange(value) {
        let labelName = this.$refs['myCascader'].getCheckedNodes()[0].pathLabels;
        this.form.people = value[value.length-1];
        this.form.name = labelName[labelName.length-1];
      },
      cancleBtn() {
        this.form.people = ''
        this.form.name =''
        this.$emit('replaceFun', false)
        this.bindingShow = false
        // this.$store.state.replaceModalShow = false
      },
      handleSizeChange(val) {
        this.page.pageSize = val
        this.getDataList()
      },
      handleCurrentChange(val) {
        this.page.pageIndex = val
        this.getDataList()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .page{
    position: relative;
    height: calc(100vh - 110px);
    padding: 20px 20px 45px 20px;
    .info_button {
      color: #4885F4;
      cursor: pointer;
    }
    .sell_name{
      padding-right: 10px;
    }
    ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }
    ::v-deep .el-dialog {
      max-height: 80vh;
      overflow: auto;
    }
    ::v-deep .el-dialog__body {
      margin-top: 25px;
      padding:30px 20px 30px 30px;
    }
    ::v-deep .el-dialog__header {
      /*background: #3489ff;*/
      position: fixed;
      width: 550px;
      z-index: 99;
      /*.el-dialog__title {*/
      /*color: #ffffff;*/
      /*}*/
      .el-dialog__headerbtn {
        top: 14px !important;
        cursor: pointer;
        /*i {*/
        /*color: #ffffff;*/
        /*}*/
      }
    }
    .container_examine{
      margin-top: 20px;
      .el-select{
        width: 90%;
      }
      .el-form--inline .el-form-item{
        width: 48%;
        margin-bottom:12px;
      }
      ::v-deep .el-select,
      ::v-deep .el-date-editor{
        width: 100%;
      }
      ::v-deep .el-form-item__label{
        font-weight: normal;
        line-height:20px;
      }

    }
  }
</style>
